from django.shortcuts import render, redirect
from apps.users.models import User
from django.http import JsonResponse
from django.contrib.auth.hashers import make_password
# Create your views here.


def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if not all([username, password]):
            return JsonResponse(data={'code': 202, 'errmsg': '参数错误'})
        # return render(request, '')
        is_exists = User.objects.filter(username=username).exists()
        if is_exists:
            return JsonResponse({'code': 201, 'msg': '账户已经存在'})
        User.objects.create_user(username=username, password=password)
        return JsonResponse({'code': 200, 'msg': '注册成功'})
    else:
        return JsonResponse(status=403, data={'code': '403', 'errmsg': '非法访问，请重试！'})


def index(request):
    return render(request, '')


def change_pwd(request):
    if request.method == 'POST':
        user_id = request.session.get('_auth_user_id')
        password = request.POST.get('password')
        new_password = make_password(password)
        if not all([user_id, new_password]):
            return JsonResponse(data={'code': 202, 'errmsg': '参数错误'})
        is_exists = User.objects.filter(id=user_id).exists()
        if not is_exists:
            return JsonResponse({'code': 201, 'msg': '账户不存在'})
        try:
            userinfo = User.objects.get(id=user_id)
            userinfo.password = new_password
            userinfo.save()
            request.session.flush()
        except Exception as e:
            return JsonResponse({'code': 501, 'msg': f'未知错误{e}'})
        return JsonResponse({'code': 200, 'msg': '修改成功'})
    else:
        return JsonResponse(status=403, data={'code': '403', 'errmsg': '行为异常，请重试'})